package com.sz.mes.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.exception.BusinessException;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;

import com.diboot.file.controller.BaseExcelFileController;
import com.diboot.file.excel.BaseExcelModel;
import com.diboot.file.excel.listener.ReadExcelListener;
import com.diboot.file.util.ExcelHelper;

import com.sz.mes.entity.Goods;
import com.sz.mes.entity.ProductTask;
import com.sz.mes.dto.ProductTaskDTO;
import com.sz.mes.excel.model.GoodsImportModel;
import com.sz.mes.mapper.ProductTaskMapper;
import com.sz.mes.service.ProductTaskService;
import com.sz.mes.vo.ProductTaskListVO;
import com.sz.mes.excel.listener.ProductTaskImportListener;
import com.sz.mes.excel.model.ProductTaskImportModel;
import com.sz.mes.excel.model.ProductTaskExportModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 生产任务 Excel处理Controller
 *
 * @author hem
 * @version 1.0
 * @date 2024-01-08
 * Copyright © szhs
 */
@RestController
@RequestMapping("/productTask/excel")
@BindPermission(name = "生产任务导入导出", code = "ProductTaskExcel")
@Slf4j
public class ProductTaskExcelController extends BaseExcelFileController {

    @Autowired
    private ProductTaskService productTaskService;

    @Autowired
    private ProductTaskMapper productTaskMapper;

    /**
     * 预览数据
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "导入预览", code = OperationCons.CODE_IMPORT)
    @PostMapping("/preview")
    public JsonResult preview(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
//        productTaskMapper.deleteAll();
//        productTaskMapper.truncateAll();
        JsonResult<Map<String, Object>> jsonResult = super.excelPreview(file, ProductTask.class, params);
        if (jsonResult.getMsg().equals("操作成功")) {
            productTaskMapper.batchUpdateTaskNum();
        }
        return jsonResult;
    }

    /**
     * 导入预览保存
     *
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "导入预览保存", code = OperationCons.CODE_IMPORT)
    @PostMapping("/previewSave")
    public JsonResult previewSave(@RequestParam Map<String, Object> params) throws Exception {
//        productTaskMapper.deleteAll();
        productTaskMapper.truncateAll();
        JsonResult<Map<String, Object>> jsonResult = super.excelPreviewSave(params);
        if (jsonResult.getMsg().equals("操作成功")) {
            productTaskMapper.batchUpdateTaskNum();
        }
        return jsonResult;
    }

    /**
     * 上传excel并保存
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "直接导入", code = OperationCons.CODE_IMPORT)
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
//        productTaskMapper.deleteAll();
        productTaskMapper.truncateAll();
        JsonResult<Map<String, Object>> jsonResult = super.uploadExcelFile(file, ProductTask.class, params);
        if (jsonResult.getMsg().equals("操作成功")) {
            productTaskMapper.batchUpdateTaskNum();
        }
        return jsonResult;

//        return super.uploadExcelFile(file, ProductTask.class, params);
    }

    @Override
    protected <T extends BaseExcelModel> void readExcelFile(InputStream inputStream, String fileExt, ReadExcelListener<T> listener) throws Exception {
        try {
            //ExcelHelper.read(inputStream, "csv".equalsIgnoreCase(fileExt) ? ExcelTypeEnum.CSV : null, listener, listener.getExcelModelClass());
            EasyExcel.read(inputStream,listener.getExcelModelClass(),listener).headRowNumber(2).excelType("csv".equalsIgnoreCase(fileExt) ? ExcelTypeEnum.CSV : null).sheet().doRead();
        } catch (Exception var5) {
            log.warn("解析excel文件失败", var5);
            if (var5 instanceof BusinessException) {
                throw var5;
            } else if (V.notEmpty(var5.getMessage())) {
                throw new Exception(var5.getMessage());
            } else {
                throw var5;
            }
        }
    }

    /**
     * 下载示例文件
     *
     * @param response
     * @throws Exception
     */
    @BindPermission(name = "导入生产任务示例文件下载", code = OperationCons.CODE_IMPORT)
    @GetMapping("/downloadExample")
    public void downloadExample(HttpServletResponse response) throws Exception {
        String fileName = "生产任务导入示例.xlsx";
        ExcelHelper.exportExcel(response, fileName, ProductTaskImportModel.class, null);
    }

    /**
     * 生产任务列表导出
     *
     * @param response
     * @return
     * @throws Exception
     */
    @BindPermission(name = "导出列表文件", code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(ProductTaskDTO productTaskDto, @RequestParam(value = "columns", required = false) List<String> columns,
                             HttpServletResponse response) throws Exception {
        QueryWrapper<ProductTask> queryWrapper = super.buildQueryWrapperByQueryParams(productTaskDto);
        List<ProductTaskListVO> productTaskList = productTaskService.getViewObjectList(queryWrapper, null, ProductTaskListVO.class);
        if (V.isEmpty(productTaskList)) {
            return new JsonResult(Status.FAIL_OPERATION, "生产任务列表为空，导出失败");
        }
        String fileName = "生产任务列表导出_" + D.today() + ".xlsx";
        List<ProductTaskExportModel> dataList = this.entityList2ExcelList(productTaskList);
        ExcelHelper.exportExcel(response, fileName, ProductTaskExportModel.class, columns, dataList);
        return null;
    }

    /**
     * 实体列表转excel列表
     *
     * @param productTaskList
     * @return
     */
    private List<ProductTaskExportModel> entityList2ExcelList(List<ProductTaskListVO> productTaskList) {
        if (V.isEmpty(productTaskList)) {
            return Collections.emptyList();
        }
        return BeanUtils.convertList(productTaskList, ProductTaskExportModel.class);
    }

    @Override
    protected ReadExcelListener<ProductTaskImportModel> getExcelDataListener() {
        return new ProductTaskImportListener();
    }


    /**
     * 上传excel并保存
     *
     * @param file
     * @param params
     * @throws Exception
     */
    @BindPermission(name = "重复数据执行更新", code = OperationCons.CODE_IMPORT)
    @PostMapping("/update")
    public JsonResult update(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {

        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        threadPool.submit(() -> {
            ArrayList<ProductTaskImportModel> productTaskImportModels = new ArrayList<>();
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                EasyExcel.read(inputStream, ProductTaskImportModel.class, new AnalysisEventListener<ProductTaskImportModel>() {
                    @Override
                    public void invoke(ProductTaskImportModel reportExcel, AnalysisContext analysisContext) {
                        // 将读取到的每一行存入reportDetails集合中
                        productTaskImportModels.add(reportExcel);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    }
                }).sheet().doRead();
            } catch (IOException e) {
                e.printStackTrace();
            }
            List<ProductTask> productTaskList = productTaskMapper.selectList(null);
            if (productTaskList.size() > 0) {
                try {
                    List<ProductTaskImportModel> goodsImportModels = BeanUtils.convertList(productTaskList, ProductTaskImportModel.class);
                    List<ProductTaskImportModel> result = productTaskImportModels.stream()
                            .filter(a -> !productTaskImportModels.contains(a))
                            .collect(Collectors.toList());
                    //后续在此处进行业务处理
                    if (result.size() > 0) {
                        for (ProductTaskImportModel productTaskImportModel : result) {
                            QueryWrapper<ProductTask> wrapper = new QueryWrapper<>();
                            wrapper.eq("receipt_num", productTaskImportModel.getReceiptNum());
                            wrapper.eq("stock_num", productTaskImportModel.getStockNum());
                            ProductTask productTaskDB = productTaskMapper.selectOne(wrapper);
                            ProductTask productTask = BeanUtils.convert(productTaskImportModel, ProductTask.class);
                            if (productTaskDB != null) {
                                Long id = productTaskDB.getId();
                                productTask.setId(id);
                                productTaskMapper.updateById(productTask);
                            } else {
                                String substringNum = productTask.getReceiptNum().substring(2);
                                productTask.setTaskNum(substringNum);
                                productTaskMapper.insert(productTask);
                            }

                        }
                    }

                } finally {
                    threadPool.shutdown();
                }
            }
        });
        return JsonResult.OK();
    }


    //批量更新数据库taskNum
    @GetMapping("/getTaskNum")
    public JsonResult getTaskNum() throws Exception {
        List<String> receiptNumList = productTaskMapper.selectReceiptNum();
        productTaskMapper.updateTaskNum(receiptNumList);
//        productTaskMapper.batchUpdateTaskNum();
//        productTaskMapper.updateTaskNum(productTaskList);
        return JsonResult.OK();
    }
}
